# import json
# from datetime import datetime
# from fake_useragent import UserAgent
import time
import requests
from lxml import etree
# import re
import random
# import os
import pymysql
import redis
# from fake_useragent import UserAgent
#
# headers = {
#         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
#         'Accept-Encoding': 'gzip, deflate, br',
#         'Accept - Language': 'zh - CN, zh;q = 0.9',
#         'User-Agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.97Safari/537.36',
#         # "Proxy-Authorization": 'Basic ' + appKey,
#     }
# url = 'https://www.baidu.com/link?url=6h0vyHirQD7a2M4cLbZCb-EMT4TZZBokF_-_vxP-G1OOxxM6GsVQmxTEy9JTRJEr&ck=5562.29.0.0.0.424.88.0&shh=www.baidu.com&wd=&eqid=dbc8f0c0002bffc7000000025f03cadf'
# url2 = 'https://www.baidu.com/link?url=wrZJfYkju4XYrdQu3b9Dj-52_gfZa1bCRSEPGit6585gliBFZjHQRldEs1KT9Lqy&ck=5831.14.0.0.0.446.460.0&shh=www.baidu.com&sht=baidu&wd=&eqid=9ce7534800004bb3000000025f040e8b'
# resp = requests.get(url=url2).text
# ul = re.findall(r'<noscript><META http-equiv="refresh" content="0;URL=\'(.*?)\'"></noscript>',resp)[0]
def myxpath(page, ruler):
    return etree.HTML(page).xpath(ruler)
def func(keyword,ip_port):
    proxies = {"http": "http://" + ip_port, "https": "https://" + ip_port}
    header = {
                'User-Agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/82.0.5104.97Safari/537.36',
            }
    headers = []
    # for i in range(1000):
    #     header = {
    #         'User-Agent': UserAgent().random,
    #     }
    #     print(header)
    #     headers.append(UserAgent().random)
    # print(len(set(headers)))
    url = 'https://m.baidu.com/s?wd={0}&pn={1}&oq={0}&bd_ck=0'.format(keyword,10)
    resp = requests.get(url=url,headers=header,proxies=proxies).text
    time.sleep(1)
    return resp

# func('西红柿的功效与作用','106.110.96.161:4258')
res = func('火龙果的功效与作用','117.26.230.252:4206')
print(res)
content_left = ''.join(myxpath(res,'//div[contains(@class,"c-result result")]//text()'))
print(content_left)
# func('西红柿的功效与作用','58.218.201.122:8782')
# li = []
# for i in range(101):
#     if i%3 == 0:
#         li.append(i)
# print(len(li))
# item = {'age':'9','sex':'girl','name':'程子涵'}
# for key,value in item.items():
#     print(key+'==='+value)
#     print(random.randint(1, 100))
#
# while True:
#     print(UserAgent().random)
#     time.sleep(2)

# now_str = datetime.now().date().strftime('%Y%m%d')
# file_dir = os.path.join('C:\\Users\Administrator\Desktop', now_str)
# if not os.path.exists(file_dir):
#     os.makedirs(file_dir)
# f = open(file_dir+'\item.txt','a')
# json.dump(item,f)
# f.close()
# li = ['a','a','a','a','b','b','c']
# while True:
#     if li:
#         value = random.choice(li)
#         print(value)
#         li.remove(value)
#     else:
#         break
# res = 5
# if isinstance(res,int):
#     print(res)
#
# # li1 = ['a','b','c',3]
# # li2 = ['a','b','f',2]
# # print(set(li1)-set(li2))
# print(type((0,)))
# a = 'love'
# b = '&*@maczh'
# if b in a:
#     print('czh')
# a = (0,)
# b = 'czh'
# float_num = '555'
# # float_num = int('{}{}'.format(float_num[0],int(float_num[1]))) +1
# float_num = float_num[:2]
# print(b[2])
# print(float_num)
# for i in range(1,5):
#     b = 'hahaha'
#     float_num = 'heiehi'
# print(b,float_num)
# try:
#     b = []
#     a = [5,6,9,4]
#     b.extend(a)
#     b.extend([])
#     b.extend(None)
#     print(b)
# except Exception as e:
#     print(e)
# # with open('a.txt','a') as f:
# #     f.write('程子涵')
#
# def save_file(take_str):
#     with open('renwu.txt','a') as f:
#         f.write(take_str+'\n')
#
# save_file('程子涵')
# save_file('你咋那么美')
# save_file('你咋那么可爱')
# db_config = {
#         'host':'127.0.0.1',
#         'port':1314,
#         'user': 'admin',
#         'password': 'Root110qwe',
#         'db': 'dcrm',
#         'charset': 'utf8',
#     }
# conn = pymysql.connect(**db_config)
# cur = conn.cursor()
# def connect_mysql_sql(cur,conn,sql_2,moshi='select'): #连接MySQL
#     cur.execute(sql_2)
#     conn.commit()
#     if moshi == 'select':
#         tuple_rcs = cur.fetchall()
#         return tuple_rcs
#     cur.close()
#     conn.close()
# mdb = redis.StrictRedis(host='103.85.85.247', port=6379, db=1, decode_responses=True, password='ma1114')  #
# # mdb.flushdb()
# # for i in range(1,20):
# #     st = f'demo-->{i}' #还可以这样玩
# #     print(st)
# se = mdb.smembers('kuaipai')
# # current_tal = mdb.scard('kuaipai_1')
# # print(se)
# for p,i in enumerate(se):
#     print(p,i)
# print(type(se))
# sms_code = ''.join(random.choice('0123456789') for i in range(4))
# print(sms_code)
# item = {'name':'czh','age':7,'birthday':'2013-06-28'}
# item['shengri'] = item['birthday']
# print(item)
# sql = 'select * from tb_user'
# sql1 = '''
# INSERT INTO `tb_teachers`(create_time, update_time, is_delete, name, title,`profile`,photo)VALUES( '2019-07-18 14:26:05.000000', '2019-07-18 14:26:12.000000', '0', '墨染', 'web高级讲师', 'python学院怪老师加大叔', '/media/avatar.jpeg');
# '''
# sql2 = '''
# INSERT INTO `tb_course_category` VALUES ('1', '2019-07-17 14:34:33.000000', '2019-07-17 14:34:36.000000', '0', 'python基础');
#
# '''
# sql3 = '''
# INSERT INTO `tb_course_category` VALUES ('2', '2019-07-17 14:34:52.000000', '2019-07-17 14:34:55.000000', '0', 'python高级');
# '''
# sql4 = "INSERT INTO `tb_course_category` VALUES ('3', '2019-07-17 14:35:20.000000', '2019-07-17 14:35:16.000000', '0', 'python框架');"
# sql5 = '''
# insert into tb_course (title, cover_url, video_url, duration, `profile`, outline, teacher_id, category_id, create_time, update_time, is_delete)values
# ('巧克力与香子兰','/media/girl_czh.jpg', 'https://maczh.cdn.bcebos.com/%E5%B7%A7%E5%85%8B%E5%8A%9B%E4%B8%8E%E9%A6%99%E5%AD%90%E5%85%B0%2F%E5%B7%A7%E5%85%8B%E5%8A%9B%E4%B8%8E%E9%A6%99%E5%AD%90%E5%85%B0-%E7%AC%AC01%E9%9B%86.mp4', 212000000, '非常好看的动漫，你值得一看哦！', '巧克力与香子兰 呼唤星辰的少女', 1, 3, now(), now(), 0);
# '''
# connect_mysql_sql(cur,conn,sql5,'insert')
